Executing Java Programs Using the java Command
Course: Core Java Training
Topic: Executing Java Programs Using the java Command
Course Link: Core Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to Executing Java Programs
Java is a platform-independent programming language that allows developers to write code once and run it on compatible systems with a Java runtime environment. After writing a Java source file and compiling it, the generated bytecode can be executed using the java command.
The java command launches the Java Virtual Machine (JVM), loads the specified class, and invokes its entry-point method, typically public static void main(String[] args). It is commonly used to run Java applications from the command line or terminal.
Understanding the java command is essential for beginners because it connects the compilation process to the actual execution of a Java program.
2. Learning Objectives
- Understand the purpose of the
java command.
- Differentiate between the
javac compiler and the java launcher.
- Compile and execute a Java program from the command line.
- Understand class names, classpaths, and the program entry point.
- Pass command-line arguments to a Java application.
- Identify and troubleshoot common execution errors.
- Run Java programs from different directories and package structures.
3. What Is the java Command?
The java command is the standard command-line launcher used to start Java applications. It starts a Java runtime, loads the requested class or supported launch target, and executes the application.
For a traditional compiled Java program, the command generally uses the class name rather than the source filename or the .class extension.
Basic Syntax
java ClassName
For example, if the compiled class is named HelloJava, execute it with:
java HelloJava
The class must be accessible through the current classpath or another configured class-loading mechanism.
4. Difference Between javac and java
The javac and java commands perform different jobs in the Java development process.
| Feature |
javac |
java |
| Purpose |
Compiles Java source code. |
Launches and executes a Java application. |
| Input |
Usually a .java source file. |
Usually a class name, module target, or supported launch target. |
| Output |
Typically generates .class bytecode files. |
Runs the requested application and displays its output. |
| Example |
javac HelloJava.java |
java HelloJava |
| Common errors |
Syntax errors, type errors, missing symbols. |
Class-loading errors, missing main method, runtime exceptions. |
Important: In the traditional compile-and-run workflow, compile the source file first and then run the resulting class.
5. Understanding the Java Execution Process
A typical Java program moves through several stages before producing output.
- Write source code: Create a Java file such as
HelloJava.java.
- Compile the source: Run
javac HelloJava.java.
- Generate bytecode: The compiler produces
HelloJava.class if compilation succeeds.
- Launch the program: Run
java HelloJava.
- Load the class: The JVM loads the class and its required dependencies.
- Invoke the entry point: The launcher calls the appropriate
main() method for a traditional application.
- Execute instructions: The JVM interprets bytecode and may compile frequently executed code into native machine instructions using its JIT compiler.
- Display output: Text printed using
System.out.println() appears in the terminal.
6. Writing Your First Java Program
Create a file named HelloJava.java and enter the following code:
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello, Java!");
System.out.println("My first Java program is running.");
}
}
Code Explanation
public class HelloJava declares a class named HelloJava.
public static void main(String[] args) defines the traditional application entry point.
System.out.println() prints text and moves the cursor to a new line.
- The closing braces define the end of the method and class.
7. Step-by-Step Guide to Running a Java Program
Step 1: Check the Java Installation
Open Command Prompt on Windows or Terminal on macOS and Linux. Check whether the Java launcher is available:
java -version
This command displays version information for the Java runtime selected by your system. The exact output depends on the installed JDK or runtime distribution.
Also check the compiler:
javac -version
If either command is not recognized, verify that a suitable JDK is installed and that its bin directory is configured in the system PATH.
Step 2: Create a Java Source File
Create a working folder, such as JavaPractice, and save the following code in a file named Welcome.java.
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Core Java!");
}
}
For a public top-level class, the source filename must match the class name, including capitalization. Here, the file must be named Welcome.java.
Step 3: Open the Terminal in the Correct Directory
Move to the folder containing the source file. For example, on Windows:
cd C:\JavaPractice
On macOS or Linux, the directory might be:
cd ~/JavaPractice
Use the actual path where you saved the file. You can list files with dir on Windows or ls on macOS and Linux.
Step 4: Compile the Java File
javac Welcome.java
If the program compiles successfully, a file named Welcome.class is normally created in the current directory. If the compiler reports errors, correct them before proceeding.
Step 5: Execute the Compiled Class
java Welcome
Expected output:
Welcome to Core Java!
Notice that the command uses Welcome, not Welcome.java or Welcome.class, in this traditional class-launching workflow.
8. Why the Class Name Is Used Without an Extension
When launching a compiled class through the traditional classpath mechanism, the Java launcher expects a class name. It locates the corresponding class file using the classpath and class-loading rules.
For example, if the compiled file is Calculator.class, use:
java Calculator
Do not normally use the following for a traditional compiled-class launch:
java Calculator.class
The latter treats the text as a class name rather than as a filename and generally fails. Modern Java versions also support source-file launch mode, such as java HelloJava.java, which runs a source file directly without a separate explicit javac step. That is a different launch mode from running an already compiled class.
9. Running a Java Program with Command-Line Arguments
Command-line arguments allow users to pass information to a Java program when starting it. In a traditional application, these values are received as strings in the String[] args parameter of the main() method.
Example Program
public class Greeting {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a name.");
return;
}
System.out.println("Hello, " + args[0] + "!");
}
}
Compile the Program
javac Greeting.java
Execute with an Argument
java Greeting Rahul
Expected output:
Hello, Rahul!
In this example, args[0] contains Rahul. Array indexes begin at zero, so the first argument is at index 0.
Passing Multiple Arguments
public class AddNumbers {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java AddNumbers <number1> <number2>");
return;
}
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
System.out.println("Sum: " + (first + second));
}
}
Compile and run:
javac AddNumbers.java
java AddNumbers 10 20
Expected output:
Sum: 30
Note: Integer.parseInt() converts a string to an integer. If a supplied value is not a valid integer, the program can throw a NumberFormatException. Real applications should validate user input or handle that exception.
10. Running Java Programs from a Different Directory
The current directory is not always the directory that contains the compiled class. You can use the -cp or -classpath option to specify where Java should search for classes.
Example Folder Structure
Project/
src/
Welcome.java
out/
Welcome.class
Compile the source into the out directory:
javac -d out src/Welcome.java
Then launch the class by specifying out as the classpath:
java -cp out Welcome
The -cp out option tells the launcher to search the out directory for the requested class and its classpath-based dependencies.
Using an Absolute Classpath
You can also provide an absolute path to the directory containing the compiled classes.
Windows example:
java -cp C:\JavaPractice\out Welcome
macOS or Linux example:
java -cp /home/user/JavaPractice/out Welcome
Replace these example paths with the actual directory on your computer.
11. Executing Java Classes Inside Packages
Java packages organize related classes and help avoid naming conflicts. If a class declares a package, the launcher must use its fully qualified class name, and the classpath must point to the root directory above the package structure.
Example Source Code
package com.example;
public class App {
public static void main(String[] args) {
System.out.println("Java package execution successful.");
}
}
Save the file as App.java in the appropriate source directory, for example src/com/example/App.java.
Compile the Packaged Class
javac -d out src/com/example/App.java
This creates the class file under out/com/example/App.class.
Run the Packaged Class
java -cp out com.example.App
Expected output:
Java package execution successful.
Do not run this class using only java App when the class belongs to com.example. Use its fully qualified name: com.example.App.
12. Important Options of the java Command
The Java launcher provides several useful options for controlling application startup.
| Option |
Purpose |
Example |
-version |
Displays Java version information. |
java -version |
-help |
Displays launcher help for the installed Java version. |
java -help |
-cp |
Specifies the classpath. |
java -cp out Welcome |
-classpath |
Long form of the classpath option. |
java -classpath out Welcome |
-jar |
Launches an executable JAR file. |
java -jar app.jar |
-Dname=value |
Sets a Java system property. |
java -Dapp.mode=test Welcome |
--class-path |
Long-form classpath option available in modern Java launchers. |
java --class-path out Welcome |
Available options may differ across Java versions. To view the supported options on your installation, use the launcher help command.
13. Running an Executable JAR File
A JAR (Java Archive) file can bundle compiled classes and other application resources. An executable JAR normally contains a manifest that identifies the application's entry-point class.
To launch an executable JAR, use:
java -jar app.jar
Replace app.jar with the actual JAR filename and path. The JAR must have an appropriate manifest entry, typically Main-Class, for this launch mode.
Example
java -jar CalculatorApp.jar
If the JAR requires external libraries, ensure that the application is packaged or configured to locate those dependencies. When using -jar, a separately supplied classpath option is not used in the same way as in ordinary class launching; follow the application's packaging and manifest configuration.
14. Understanding the Classpath
The classpath specifies locations where the Java launcher and class loader can search for application classes and libraries in traditional classpath-based applications. These locations can include directories and JAR files.
Classpath with a Directory
java -cp out Welcome
Classpath with a JAR File
java -cp "lib/example-library.jar;out" Welcome
On Windows, the classpath separator is a semicolon (;). On macOS and Linux, it is a colon (:).
macOS or Linux example:
java -cp "lib/example-library.jar:out" Welcome
If you do not specify a classpath, the default classpath behavior commonly uses the current directory for classpath-based launching, unless other settings or launch modes apply. Explicitly specifying the classpath can make execution more predictable.
15. Source-File Launch Mode in Modern Java
Modern Java versions support running a single source file directly using the Java launcher. This can be useful for quick examples, demonstrations, and small utilities.
For a file named HelloJava.java, use:
java HelloJava.java
The launcher compiles and runs the source file in source-file mode. For this simple workflow, you do not need to run javac separately first.
Compare the two approaches:
| Workflow |
Commands |
Use case |
| Traditional compiled-class mode |
javac HelloJava.java
java HelloJava |
Learning compilation, managing class files, and building applications. |
| Source-file launch mode |
java HelloJava.java |
Quick experiments and small standalone programs. |
For package-based applications, projects with multiple source files, or applications with external dependencies, use a build tool or an appropriate compilation and launch configuration.
16. Common Errors When Executing Java Programs
| Error |
Possible Cause |
Solution |
'java' is not recognized |
Java is not installed or its executable directory is not on PATH. |
Install a suitable JDK and configure the PATH environment variable. |
Could not find or load main class |
Incorrect class name, missing class file, or incorrect classpath. |
Verify the class name, compiled output, working directory, and classpath. |
Main method not found |
The class does not contain a compatible application entry point. |
Check the main method signature and ensure it is declared correctly. |
ClassNotFoundException |
An application attempts to load a class that is unavailable to its class loader. |
Check dependencies, classpath configuration, and class-loading logic. |
NoClassDefFoundError |
A required class definition is unavailable during execution, or initialization previously failed. |
Inspect the complete error message, dependency availability, and earlier exceptions. |
UnsupportedClassVersionError |
The runtime cannot load bytecode produced for a newer Java version. |
Use a compatible runtime or compile for the target Java release. |
Could not find or load main class Welcome.class |
The class filename extension was included in a traditional class-launch command. |
Use java Welcome. |
NumberFormatException |
A program tried to parse invalid numeric text. |
Validate command-line input and handle invalid values. |
17. Troubleshooting Java Execution Problems
Problem 1: The Program Compiles but Does Not Run
Check whether the generated .class file is in the expected directory. Then verify that the command uses the correct class name and classpath.
javac Welcome.java
dir
java Welcome
On macOS or Linux, use ls instead of dir.
Problem 2: Incorrect Class Name
Java class names are case-sensitive. If the class is named Welcome, running java welcome may fail because the names differ in capitalization.
Problem 3: Wrong Working Directory
If the terminal is open in another directory, the launcher might not find the compiled class. Navigate to the correct location or specify the classpath explicitly.
Problem 4: Missing Main Method
A traditional Java application should contain the appropriate entry point:
public static void main(String[] args)
Ensure the method is inside the class you are launching and has the correct spelling, capitalization, modifiers, return type, and parameter type.
Problem 5: Java Version Mismatch
Compare the Java compiler and runtime versions:
javac -version
java -version
If the bytecode requires a newer runtime than the one being used, install or select a compatible runtime or compile with an appropriate release target.
18. Best Practices for Running Java Programs
- Use a consistent naming convention for Java classes and source files.
- Keep source files, compiled classes, and libraries organized in separate directories when appropriate.
- Use explicit classpaths when working with multiple directories or external libraries.
- Check compiler output before attempting to launch the program.
- Use the fully qualified class name for classes inside packages.
- Validate command-line arguments before processing them.
- Read the complete error message and identify the first relevant cause.
- Use a compatible JDK or runtime version for the compiled application.
- For larger projects, use build tools such as Maven or Gradle to manage dependencies and repeatable build tasks.
- Avoid depending on a machine-specific working directory for application resources.
- Use source-file launch mode for simple experiments, but understand the traditional compile-and-run process as well.
19. Practical Example: Student Information Program
This example demonstrates how to execute a Java program that accepts student information through command-line arguments.
Source Code
public class StudentInfo {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java StudentInfo <name> <course>");
return;
}
String name = args[0];
String course = args[1];
System.out.println("Student Name: " + name);
System.out.println("Course: " + course);
System.out.println("Status: Enrolled");
}
}
Compile the Program
javac StudentInfo.java
Run the Program
java StudentInfo Priya "Core Java"
Expected Output
Student Name: Priya
Course: Core Java
Status: Enrolled
The quotation marks keep Core Java together as one command-line argument even though it contains a space.
20. Practical Exercises
Exercise 1: Display a Message
- Create a class named
MessageApp.
- Print a welcome message from the
main() method.
- Compile it using
javac.
- Execute it using the
java command.
Exercise 2: Add Two Numbers
- Create a class named
SumApp.
- Accept two numeric command-line arguments.
- Convert the arguments to integers.
- Display their sum and handle invalid input appropriately.
Exercise 3: Execute a Packaged Class
- Create a class inside a package named
training.
- Compile it into a separate output directory using
javac -d.
- Run it using
-cp and its fully qualified class name.
Exercise 4: Troubleshoot a Classpath Error
- Compile a class into a folder named
out.
- Try launching it without specifying the classpath from a different directory.
- Observe the error and resolve it using
java -cp out ClassName with the correct path.
21. Interview Questions and Answers
Q1. What is the purpose of the java command?
Answer: The java command launches a Java application. In traditional class-launch mode, it loads the specified class and invokes its main method.
Q2. What is the difference between java and javac?
Answer: javac compiles Java source code into bytecode, while java launches the application using the Java runtime.
Q3. How do you execute a compiled Java class?
Answer: Use java ClassName, assuming the class is available on the classpath and contains a suitable entry point.
Q4. Why should you not add .class to the class name?
Answer: In traditional class-launch mode, the launcher expects a class name rather than a class filename. For example, use java Welcome, not java Welcome.class.
Q5. What does the -cp option do?
Answer: The -cp option specifies the classpath locations that the launcher uses to locate classes and libraries.
Q6. How do you run a Java class inside a package?
Answer: Specify the classpath root and the fully qualified class name. For example, java -cp out com.example.App.
Q7. What are command-line arguments in Java?
Answer: They are values supplied after the class name when launching the program. A traditional main method receives them through the String[] args parameter.
Q8. Can a Java source file be executed without explicitly running javac?
Answer: Yes. Modern Java versions support source-file launch mode, for example java HelloJava.java. This differs from launching a previously compiled class.
Q9. What does “Could not find or load main class” mean?
Answer: The launcher could not locate or load the requested class. Common causes include a wrong class name, incorrect classpath, missing class file, or package mismatch.
Q10. What is the purpose of java -jar?
Answer: It launches an executable JAR whose manifest identifies the application entry point.
22. Quick Revision Checklist
- The
javac command compiles source files.
- The
java command launches Java applications.
- Traditional class launching uses the class name without the
.class extension.
- A public top-level class normally uses a source filename matching its class name.
- The main method is the conventional entry point for a simple Java application.
- The
-cp option specifies the classpath.
- Packaged classes require their fully qualified names.
- Command-line arguments are received through
String[] args.
- Modern Java supports source-file launch mode.
- The
-jar option launches an executable JAR.
- Check Java versions and classpaths when troubleshooting execution errors.
23. Conclusion
The java command is a fundamental part of Core Java development. It allows developers to launch applications, execute compiled classes, pass command-line arguments, work with packages, and run executable JAR files. Learning the difference between compiling with javac and executing with java helps beginners understand the Java development workflow and troubleshoot common problems confidently.
Practice running Java programs from the terminal, experimenting with classpaths, and passing command-line arguments to strengthen your understanding of Java application execution.
Explore more learning opportunities through the JustAcademy Core Java Training Course, register for a course demo, or visit the JustAcademy website.